package com.gel.codegeneration.core.saver;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.gel.codegeneration.ai.model.enums.CodeGenTypeEnum;
import com.gel.codegeneration.common.constant.AppConstant;
import com.gel.codegeneration.common.enums.ErrorCode;
import com.gel.codegeneration.utils.ThrowUtils;

import java.io.File;

/**
 * @BelongsProject: code-generation-platform
 * @BelongsPackage: com.gel.codegeneration.core.saver
 * @Author: gel
 * @CreateTime: 2025-08-22  15:51
 * @Description: TODO 文件保存模板
 * @Version: 1.0
 */
public abstract class CodeFileSaveTemplate<T> {
    private static final String ROOT_PATH = AppConstant.CODE_OUTPUT_ROOT_DIR;

    public final File saveCode(T result,Long appId) {
        //验证输入
        validateInput(result);
        //构建唯一目录
        String dirPath = buildUniqueDirPath(appId);

        //保存文件
        saveFile(result,dirPath);

        //返回文件目录
        return new File(dirPath);
    }




    //构建唯一目录
    private final String buildUniqueDirPath(Long appId) {
        String value = getCodeType().getValue();
        String uniqueDirName = String.format("%s_%s", value, appId);
        String uniquePath = ROOT_PATH + File.separator + uniqueDirName;
        FileUtil.mkdir(uniquePath);
        return uniquePath;
    }
    //写入
    public final void writeFile(String content, String path,String fileName) {
        String filePath = path + File.separator + fileName;
        if (content != null) {
            FileUtil.writeUtf8String(content, filePath);
        } else {
            FileUtil.writeUtf8String("", filePath);
        }
    }

    //验证输入
    protected void validateInput(T result) {
        ThrowUtils.throwIf(result == null, ErrorCode.PARAMS_ERROR, "代码结果对象不能为空");

    }
    //获取代码类型
    protected abstract CodeGenTypeEnum getCodeType() ;
    //保存文件
    protected abstract void saveFile(T t, String dirPath);


}
